let dbUtil = require('db-util')
const uniID = require('uni-id')
let db = uniCloud.database()
let dbCmd = db.command
let $ = dbCmd.aggregate
const errParams = {
	errCode: 400,
	errMsg: '参数错误！'
}
const errResNotFound = {
	errCode: 501,
	errMsg: '实体不存在！'
}
module.exports = {
	_before: async function () { // 通用预处理器
		const token = this.getUniIdToken()
		if (!token) {
			throw new Error('未登录')
		}
		const payload = await uniID.checkToken(token)
		let {
			code,
			uid,
			permission
		} = payload
		if (code) {
			throw new Error('未登录')
		}
		this.uid = uid
		this.permission = permission
	},
	
	async completeProfile({
		avatar,
		nickname
	}) {
		if (!avatar || !nickname) {
			return errParams
		}
		await dbUtil.updateById({
			collection: 'uni-id-users',
			data: {
				_id: this.uid,
				avatar,
				nickname
			}
		})
		return {
			errCode: 0
		}
	}
}
